//
//  SDTimeLineCellCommentView.m
//  GSD_WeiXin(wechat)
//
//  Created by gsd on 16/2/25.
//  Copyright © 2016年 GSD. All rights reserved.
//

/*
 
 *********************************************************************************
 *
 * GSD_WeiXin
 *
 * QQ交流群: 459274049
 * Email : gsdios@126.com
 * GitHub: https://github.com/gsdios/GSD_WeiXin
 * 新浪微博:GSD_iOS
 *
 * 此“高仿微信”用到了很高效方便的自动布局库SDAutoLayout（一行代码搞定自动布局）
 * SDAutoLayout地址：https://github.com/gsdios/SDAutoLayout
 * SDAutoLayout视频教程：http://www.letv.com/ptv/vplay/24038772.html
 * SDAutoLayout用法示例：https://github.com/gsdios/SDAutoLayout/blob/master/README.md
 *
 *********************************************************************************
 
 */

#import "FriendNewLineCellCommentView.h"
#import "UIView+SDAutoLayout.h"
#import "SDTimeLineCellModel.h"
#import "MLLinkLabel.h"
#import "MessageModelManager.h"
#import "FriendLineViewController.h"
@interface FriendNewLineCellCommentView () <MLLinkLabelDelegate>

@property (nonatomic, strong) NSArray *likeItemsArray;
@property (nonatomic, strong) NSArray *commentItemsArray;

@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic, strong) MLLinkLabel *likeLabel;


@property (nonatomic, strong) NSMutableArray *commentLabelsArray;
@property (nonatomic, strong) NSMutableArray *commentTimeLabArray;
@property (nonatomic, strong) NSMutableArray *commentImageArray;
@property (nonatomic, strong) NSMutableArray *commentlinArr;


@property (nonatomic, strong) UIImageView *messageImg;




@end

@implementation FriendNewLineCellCommentView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    _bgImageView = [UIImageView new];
    UIImage *bgImage = [[UIImage imageNamed:@"Friend_LikeCmtBg"] stretchableImageWithLeftCapWidth:40 topCapHeight:30];
    _bgImageView.image = bgImage;
    _bgImageView.backgroundColor = RGB(235, 235, 235);
    [self addSubview:_bgImageView];
    
    _likeLabel = [MLLinkLabel new];
    _likeLabel.font = [UIFont systemFontOfSize:14];
    _likeLabel.linkTextAttributes = @{NSForegroundColorAttributeName : TimeLineCellHighlightedColor};
    _likeLabel.isAttributedContent = YES;
    _likeLabel.delegate = self;
    [self addSubview:_likeLabel];
    

    

    _messageImg = [UIImageView new];
    
    _messageImg.image = [UIImage imageNamed:@"news_details_message"];
    [self addSubview:_messageImg];

    
    _bgImageView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
}

- (void)setCommentItemsArray:(NSArray *)commentItemsArray {
    _commentItemsArray = commentItemsArray;
    
    long originalLabelsCount = self.commentLabelsArray.count;
    long needsToAddCount = commentItemsArray.count > originalLabelsCount ? (commentItemsArray.count - originalLabelsCount) : 0;
    for (int i = 0; i < needsToAddCount; i++) {
        MLLinkLabel *label = [MLLinkLabel new];
        UIColor *highLightColor = TimeLineCellHighlightedColor;
        label.linkTextAttributes = @{NSForegroundColorAttributeName : highLightColor};
        label.font = [UIFont systemFontOfSize:14];
        label.delegate = self;
        [self addSubview:label];
        
        
        UILabel *timelab = [UILabel new];
        
        timelab.font = FontP(13);
        timelab.textAlignment = NSTextAlignmentCenter;
        timelab.textColor = ColorI(0x802e353f);
        [timelab sizeToFit];

        [self addSubview:timelab];
        UIImageView *imgView = [UIImageView new];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.layer.cornerRadius = 17.5;
        
        imgView.layer.masksToBounds=YES;

        
        [self addSubview:imgView];

        
        UILabel *linLab = [UILabel new];
        linLab.backgroundColor = RGB(222, 222, 222);
        
        [self addSubview:linLab];

        [self.commentlinArr addObject:linLab];
        [self.commentLabelsArray addObject:label];
        [self.commentTimeLabArray addObject:timelab];
        [self.commentImageArray addObject:imgView];
    }
    
    for (int i = 0; i < commentItemsArray.count; i++) {
        NSDictionary *dic = commentItemsArray[i];
        Commentlist *model = [Commentlist getCommentlistWithDictionary:dic];
        MLLinkLabel *label = self.commentLabelsArray[i];

        label.delegate = self;
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithCommentItemModel:model];
        }
        label.attributedText = model.attributedContent;
        
        UILabel *timeLab = self.commentTimeLabArray[i];
        timeLab.text = model.createTime;
        
        UIImageView *imgView = self.commentImageArray[i];
        [imgView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(model.photo)] placeholderImage:[UIImage imageNamed:@"llustration"]];
        
        
        UILabel *linLab = self.commentlinArr[i];
        linLab.backgroundColor = RGB(222, 222, 222);
        
    }
}

- (void)setLikeItemsArray:(NSArray *)likeItemsArray {
    _likeItemsArray = likeItemsArray;
    NSTextAttachment *attach = [NSTextAttachment new];
    attach.image = [UIImage imageNamed:@"Friend_Likepraise"];
    attach.bounds = CGRectMake(0, -3, 16, 16);
    NSAttributedString *likeIcon = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:likeIcon];
    
    for (int i = 0; i < likeItemsArray.count; i++) {
        NSDictionary *dic = likeItemsArray[i];
        
        Praiselist *model = [Praiselist getPraiselistWithDictionary:dic];
        if (i > 0) {
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"，"]];
        }
        
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithLikeItemModel:model];
        }
        [attributedText appendAttributedString:model.attributedContent];
    }
    
    _likeLabel.attributedText = [attributedText copy];
}

- (NSMutableArray *)commentLabelsArray {
    if (!_commentLabelsArray) {
        _commentLabelsArray = [NSMutableArray new];
    }
    return _commentLabelsArray;
}

- (NSMutableArray *)commentTimeLabArray{
    if (!_commentTimeLabArray) {
        _commentTimeLabArray = [NSMutableArray new];
    }
    return _commentTimeLabArray;
}

-(NSMutableArray *)commentImageArray{
    if (!_commentImageArray) {
        _commentImageArray = [NSMutableArray new];
    }
    return _commentImageArray;
}


- (NSMutableArray *)commentlinArr{
    if (!_commentlinArr) {
        _commentlinArr = [NSMutableArray new];
    }
    return _commentlinArr;
}


- (void)setupWithLikeItemsArray:(NSArray *)likeItemsArray commentItemsArray:(NSArray *)commentItemsArray {
    self.likeItemsArray = likeItemsArray;
    self.commentItemsArray = commentItemsArray;
    
    
    
    
    if (self.commentLabelsArray.count) {
        [self.commentLabelsArray enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL *stop) {
            [label sd_clearAutoLayoutSettings];
            label.hidden = YES;
        }];
    }
    if (!commentItemsArray.count && !likeItemsArray.count) {
        self.fixedWidth = @(0); // 如果没有评论或者点赞，设置commentview的固定宽度为0（设置了fixedWith的控件将不再在自动布局过程中调整宽度）
        self.fixedHeight = @(0); // 如果没有评论或者点赞，设置commentview的固定高度为0（设置了fixedHeight的控件将不再在自动布局过程中调整高度）
        return;
    } else {
        self.fixedHeight = nil; // 取消固定宽度约束
        self.fixedWidth = nil; // 取消固定高度约束
    }
    CGFloat margin = 5;
    UIView *lastTopView = nil;
    
    
    
    if (likeItemsArray.count) {
        _likeLabel.sd_resetLayout
        .leftSpaceToView(self, margin)
        .rightSpaceToView(self, margin)
        .topSpaceToView(lastTopView, 10)
        .autoHeightRatio(0);
        
        lastTopView = _likeLabel;
    } else {
        _likeLabel.attributedText = nil;
        _likeLabel.sd_resetLayout
        .heightIs(0);
    }

    
    for (int i = 0; i < self.commentItemsArray.count; i++) {
        UILabel *label = (UILabel *)self.commentLabelsArray[i];
        label.hidden = NO;
        label.font =FontP(15);
        CGFloat topMargin = (i == 0 && likeItemsArray.count == 0) ? 10 : 5;
        label.sd_layout
        .leftSpaceToView(self, 70)
        .rightSpaceToView(self, 65)
        .topSpaceToView(lastTopView, topMargin)
        .autoHeightRatio(0);
       
        if (i == 0) {
            _messageImg.sd_layout
            .leftSpaceToView(self, 8)
            .widthIs(15)
            .topSpaceToView(lastTopView, topMargin+5)
            .heightIs(15);
        }

        
        
    
        UIImageView *imgView = (UIImageView *)self.commentImageArray[i];
        imgView.sd_layout
        .leftSpaceToView(_messageImg, 7)
        .widthIs(35)
        .topSpaceToView(lastTopView, topMargin+5)
        .heightIs( 35);

        
        UILabel *timeLab = (UILabel *)self.commentTimeLabArray[i];
        timeLab.sd_layout
        .leftSpaceToView(self, KScreenWidth-180)
        .widthIs(160)
        .topSpaceToView(lastTopView, topMargin)
        .heightIs( 15);

        UILabel *linLab = (UILabel *)self.commentlinArr[i];
        linLab.sd_layout
        .leftSpaceToView(self, 15)
        .rightSpaceToView(self, 5)
        .heightIs(1)
        .topSpaceToView(lastTopView, 3);

  
        label.isAttributedContent = YES;
        lastTopView = label;
    }
    
 


    
    [self setupAutoHeightWithBottomView:lastTopView bottomMargin:6];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];


}

#pragma mark - private actions

- (NSMutableAttributedString *)generateAttributedStringWithCommentItemModel:(Commentlist *)model {
    NSString *text = model.nickName;


    if (model.toNickName.length) {
        text = [text stringByAppendingString:[NSString stringWithFormat:@"\n回复%@ ", model.toNickName]];
        text = [text stringByAppendingString:[NSString stringWithFormat:@": %@", model.content]];

    }else{
        text = [text stringByAppendingString:[NSString stringWithFormat:@"\n %@", model.content]];

    }
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    UIColor *highLightColor = [UIColor blueColor];
    [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : @(model.uid).stringValue} range:[text rangeOfString:model.nickName]];
    if (model.toNickName) {
        [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : @(model.replyId).stringValue} range:[text rangeOfString:model.toNickName]];
    }
    return attString;
}

- (NSMutableAttributedString *)generateAttributedStringWithLikeItemModel:(Praiselist *)model {
    NSString *text = model.nickName;

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    UIColor *highLightColor = [UIColor blueColor];
    [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : @(model.uid).stringValue} range:[text rangeOfString:model.nickName]];
    return attString;
}

#pragma mark - MLLinkLabelDelegate
//点击评论 回复

- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText linkLabel:(MLLinkLabel *)linkLabel {
 
    NSLog(@"linkText========%@==========%@",linkText,link.linkValue);
    [self replayer:link.linkValue link:linkText];
}
//点击评论 回复
- (void)replayer:(NSString *)str link:(NSString *)link{
    
    if ([self.delegate respondsToSelector:@selector(replycommentId:username:)]) {
        [self.delegate replycommentId:str username:link];
    }
}
@end
